using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using XNA.Common;
using System.IO;
using XNA.Common.Map;
using XNA.Common.Objects;

namespace TestGame
{
	public class World : GameObject
	{
		#region CONSTRUCTION

		public World (TestGame game)
		{
			_game = game;
		}

		#endregion

		#region PROPERTIES

		public Texture2D Map
		{
			get;
			set;
		}

		public Texture2D FloorTexture
		{
			get;
			set;
		}

		public Texture2D WallTexture
		{
			get;
			set;
		}

		public Texture2D CeilingTexture
		{
			get;
			set;
		}

		public ModelData TorchModel
		{
			get;
			set;
		}

		#endregion

		#region METHODS (PUBLIC)

		public override void Initialize ()
		{
			base.Initialize ();
		}

		public override void LoadContent (ContentManager content)
		{
			var effect = content.Load<Effect> ("StandardEffects");
			FloorTexture = content.Load<Texture2D> ("Textures/Terrain/mulchground");
			WallTexture = content.Load<Texture2D> ("Textures/Terrain/GraniteTechno");
			CeilingTexture = content.Load<Texture2D> ("Textures/Terrain/CorrugatedMetal");
			Map = content.Load<Texture2D> ("Maps/SimpleRoom/floorplan");

			var model = content.Load<Model> ("Models/torch");
			var texture = content.Load<Texture2D> ("Models/texture_torch");
			TorchModel = new ModelData (
				model, 
				texture, 
				effect,
				Matrix.CreateScale (3) * Matrix.CreateTranslation (-3, 0, 0));

			_map = MapLoader.LoadMap (
				Map,
				new List<Texture2D> () { FloorTexture, CeilingTexture, WallTexture },
				new List<ElementData> () {
					new ElementData (Color.Yellow, TorchModel, true),
					new ElementData (Color.Blue),
				},
				16,
				32);
		}

		public override void Update (GameTime gameTime)
		{
			base.Update (gameTime);
		}

		public override void Draw (GameTime gameTime)
		{
			foreach (var vertices in _map.Vertices)
			{
				PaintBrush.Brush.Draw (
					Matrix.Identity,
					Technique.TexturedNoShading,
					vertices.Texture,
					vertices.Vertices.ToArray());
			}

			foreach (var element in _map.Elements)
			{
				if (element.ModelData != null)
				{
					element.Draw (gameTime);
				}
			}

			base.Draw (gameTime);
		}

		#endregion

		#region FIELDS

		private TestGame _game;
		private Map _map;

		#endregion
	}
}
